package examples.game.agent;

import framework.agent.AbstractAgent;

import examples.game.msgservice.AnswerMsg;
import examples.game.BullsAndCows;
import examples.game.Digits;
import examples.game.Match;
import examples.game.msgservice.GameStartMsg;
import examples.game.msgservice.NextMoveMsg;
import framework.Message;

public class GameAgent extends AbstractAgent {

	private static final String NAME = "BullsAndCowsAgent";
	private static GameAgent sole;

	protected GameAgent(String agentName) {
		super(agentName);
	}

	public static GameAgent getSole() {
		if (sole == null) {
			sole = new GameAgent(NAME);
		}
		return sole;
	}

	private <M extends Message> M sendAndReceiveMsg(Message msg) {
		return sendAndWait(msg, "BullsAndCows");
	}

	public Digits start() {
		/**/log.info("do you wanna play?");
		Message msg = new GameStartMsg(NAME);
		NextMoveMsg move = sendAndReceiveMsg(msg);
		return new Digits(move.getDigits());
	}

	public Match move(Digits digits) {
		Message move = new NextMoveMsg(digits);
		AnswerMsg answer = sendAndReceiveMsg(move);
		return new Match(answer.getBulls(), answer.getCows());
	}

	public Digits answer(Match match) {
		Message answer = new AnswerMsg(match);
		NextMoveMsg move = sendAndReceiveMsg(answer);
		return new Digits(move.getDigits());
	}

	public static void main(String[] args) {
		GameAgent agent = GameAgent.getSole();
		BullsAndCows game = new BullsAndCows();
		//System.out.println("secret: " + game.secret);
		Digits move = agent.start();
		while(true) {
			Match myAnswer = game.getAnswer(move);
			log.info(move + " -> " + myAnswer);
			Digits myMove = game.nextMove();
			log.info(myMove);
			Match answer = agent.move(myMove);
			game.setAnswer(answer);
			if (answer.getBulls() == BullsAndCows.NUM_DIGITS) {
				log.info("win");
				break;
			}
			//log.info(myMove + " -> " + answer);
			if (myAnswer.getBulls() == BullsAndCows.NUM_DIGITS) {
				log.info("lose");
				// TODO agent.answer(myAnswer);
				break;
			}
			move = agent.answer(myAnswer);
		}
	}
}
